<template>
  <div class="form-container">
    <div class="header">
      <el-button icon="el-icon-back" @click="goBack" class="back-btn">返回</el-button>
      <h1 style="text-align: center;">深圳市艾美思普科技有限公司 文件发放与回收记录</h1>
    </div>

    <el-form ref="form" :model="formData" :rules="rules" label-width="100px" class="main-form">
      <el-card class="form-card">
        <div slot="header" class="card-header">
          <span>基本信息</span>
          <div class="header-operations" v-if="!isView">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">新增文件(重置)</el-button>
          </div>
          <el-button type="primary" size="small" icon="el-icon-view" @click="goToList">列表</el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文件类别" prop="fileCategory">
              <el-input v-model="formData.fileCategory" :disabled="isView"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="页次" prop="pageNumber">
              <el-input-number v-model="formData.pageNumber" :disabled="isView" :min="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文件编号" prop="fileNumber">
              <el-input v-model="formData.fileNumber" :disabled="isView"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="formData.fileName" :disabled="isView"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="table-card">
        <div slot="header" class="table-header">
          <div class="header-left">
            <span class="header-title">发放与回收记录</span>
            <span class="record-count" v-if="formData.records.length > 0">（共 {{formData.records.length}} 条记录）</span>
          </div>
          <div class="header-operations">
            <el-tooltip content="新增记录" placement="top" v-if="!isView">
              <el-button type="primary" size="small" circle icon="el-icon-plus" @click="addRecord"></el-button>
            </el-tooltip>
          </div>
        </div>
        <el-table :data="formData.records" border stripe size="small" class="record-table">
          <el-table-column label="版本" width="100" fixed="left">
            <template slot-scope="scope">
              <el-form-item :prop="'records.' + scope.$index + '.version'" :rules="rules.version" class="table-form-item">
                <el-input v-model="scope.row.version" :disabled="isView" size="small"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="发放日期" width="280" fixed="left">
            <template slot-scope="scope">
              <el-form-item :prop="'records.' + scope.$index + '.issueDate'" :rules="rules.issueDate" class="table-form-item">
                <el-date-picker
                  v-model="scope.row.issueDate"
                  type="date"
                  :disabled="isView"
                  size="small"
                  style="width: 250px"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  placeholder="选择发放日期">
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="生产部门" min-width="280">
            <template slot-scope="scope">
              <div class="department-cell">
                <el-form-item :prop="'records.' + scope.$index + '.productionCopies'" :rules="rules.copies" class="table-form-item">
                  <el-input-number v-model="scope.row.productionCopies" :min="0" :disabled="isView" size="small" class="copies-input"></el-input-number>
                </el-form-item>
                <el-form-item :prop="'records.' + scope.$index + '.productionSignature'" class="table-form-item">
                  <el-input v-model="scope.row.productionSignature" placeholder="签名" :disabled="isView" size="small" class="signature-input"></el-input>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="品质部门" min-width="280">
            <template slot-scope="scope">
              <div class="department-cell">
                <el-form-item :prop="'records.' + scope.$index + '.qualityCopies'" :rules="rules.copies" class="table-form-item">
                  <el-input-number v-model="scope.row.qualityCopies" :min="0" :disabled="isView" size="small" class="copies-input"></el-input-number>
                </el-form-item>
                <el-form-item :prop="'records.' + scope.$index + '.qualitySignature'" class="table-form-item">
                  <el-input v-model="scope.row.qualitySignature" placeholder="签名" :disabled="isView" size="small" class="signature-input"></el-input>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="工程部门" min-width="280">
            <template slot-scope="scope">
              <div class="department-cell">
                <el-form-item :prop="'records.' + scope.$index + '.engineeringCopies'" :rules="rules.copies" class="table-form-item">
                  <el-input-number v-model="scope.row.engineeringCopies" :min="0" :disabled="isView" size="small" class="copies-input"></el-input-number>
                </el-form-item>
                <el-form-item :prop="'records.' + scope.$index + '.engineeringSignature'" class="table-form-item">
                  <el-input v-model="scope.row.engineeringSignature" placeholder="签名" :disabled="isView" size="small" class="signature-input"></el-input>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="物控部门" min-width="280">
            <template slot-scope="scope">
              <div class="department-cell">
                <el-form-item :prop="'records.' + scope.$index + '.materialControlCopies'" :rules="rules.copies" class="table-form-item">
                  <el-input-number v-model="scope.row.materialControlCopies" :min="0" :disabled="isView" size="small" class="copies-input"></el-input-number>
                </el-form-item>
                <el-form-item :prop="'records.' + scope.$index + '.materialControlSignature'" class="table-form-item">
                  <el-input v-model="scope.row.materialControlSignature" placeholder="签名" :disabled="isView" size="small" class="signature-input"></el-input>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="研发部门" min-width="280">
            <template slot-scope="scope">
              <div class="department-cell">
                <el-form-item :prop="'records.' + scope.$index + '.researchCopies'" :rules="rules.copies" class="table-form-item">
                  <el-input-number v-model="scope.row.researchCopies" :min="0" :disabled="isView" size="small" class="copies-input"></el-input-number>
                </el-form-item>
                <el-form-item :prop="'records.' + scope.$index + '.researchSignature'" class="table-form-item">
                  <el-input v-model="scope.row.researchSignature" placeholder="签名" :disabled="isView" size="small" class="signature-input"></el-input>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="业务部门" min-width="280">
            <template slot-scope="scope">
              <div class="department-cell">
                <el-form-item :prop="'records.' + scope.$index + '.businessCopies'" :rules="rules.copies" class="table-form-item">
                  <el-input-number v-model="scope.row.businessCopies" :min="0" :disabled="isView" size="small" class="copies-input"></el-input-number>
                </el-form-item>
                <el-form-item :prop="'records.' + scope.$index + '.businessSignature'" class="table-form-item">
                  <el-input v-model="scope.row.businessSignature" placeholder="签名" :disabled="isView" size="small" class="signature-input"></el-input>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="光电部门" min-width="280">
            <template slot-scope="scope">
              <div class="department-cell">
                <el-form-item :prop="'records.' + scope.$index + '.photoelectricCopies'" :rules="rules.copies" class="table-form-item">
                  <el-input-number v-model="scope.row.photoelectricCopies" :min="0" :disabled="isView" size="small" class="copies-input"></el-input-number>
                </el-form-item>
                <el-form-item :prop="'records.' + scope.$index + '.photoelectricSignature'" class="table-form-item">
                  <el-input v-model="scope.row.photoelectricSignature" placeholder="签名" :disabled="isView" size="small" class="signature-input"></el-input>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="回收记录" width="280" fixed="right">
            <template slot-scope="scope">
              <div class="recycle-cell">
                <el-form-item :prop="'records.' + scope.$index + '.recycleDate'" :rules="rules.recycleDate" class="table-form-item">
                  <el-date-picker
                    v-model="scope.row.recycleDate"
                    type="date"
                    :disabled="isView"
                    size="small"
                    style="width: 255px"
                    value-format="yyyy-MM-dd"
                    :picker-options="recyclePickerOptions(scope.row.issueDate)"
                    placeholder="选择回收日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item :prop="'records.' + scope.$index + '.recycler'" class="table-form-item">
                  <el-input v-model="scope.row.recycler" placeholder="回收人" :disabled="isView" size="small"></el-input>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="!isView" label="操作" width="60" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="removeRecord(scope.$index)" icon="el-icon-delete" style="color: #F56C6C"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <div class="footer">
        <p class="form-info">表单编号及版本：AM-FR-0007 A/0 生效日期：2006 年 11 月 1 日 保存年限:长期</p>
        <div class="button-group">
          <el-button v-if="!isView" type="primary" @click="handleSave" :loading="saving">保存</el-button>
          <el-button @click="$emit('success')">关闭</el-button>
        </div>
      </div>
    </el-form>
    </div>
  </template>
  
  <script>
import { getFileById, saveFile } from '@/api/ff'

export default {
  name: 'Ffhuishous',
  data() {
    // 自定义回收日期验证规则
    const validateRecycleDate = (rule, value, callback) => {
      const index = rule.fullField.match(/\d+/)[0];
      const issueDate = this.formData.records[index].issueDate;
      
      if (!value) {
        callback();
        return;
      }

      if (!issueDate) {
        callback(new Error('请先选择发放日期'));
        return;
      }

      try {
        const recycleTime = new Date(value).getTime();
        const issueTime = new Date(issueDate).getTime();
        
        if (recycleTime < issueTime) {
          callback(new Error('回收日期不能早于发放日期'));
        } else {
          callback();
        }
      } catch (error) {
        callback(new Error('日期格式不正确'));
      }
    };

    return {
      saving: false,
      formData: {
        id: null,
        fileCategory: '',
        pageNumber: 1,
        fileNumber: '',
        fileName: '',
        records: []
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }],
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      rules: {
        fileCategory: [{ required: true, message: '请输入文件类别', trigger: 'blur' }],
        fileNumber: [{ required: true, message: '请输入文件编号', trigger: 'blur' }],
        fileName: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
        version: [{ required: true, message: '请输入版本', trigger: 'blur' }],
        issueDate: [
          { required: true, message: '请选择发放日期', trigger: 'change' },
          { 
            validator: (rule, value, callback) => {
              if (!value) {
                callback();
                return;
              }
              try {
                const date = new Date(value);
                if (isNaN(date.getTime())) {
                  callback(new Error('日期格式不正确'));
                } else {
                  callback();
                }
              } catch (error) {
                callback(new Error('日期格式不正确'));
              }
            }, 
            trigger: 'change' 
          }
        ],
        copies: [{ type: 'number', min: 0, message: '份数不能小于0', trigger: 'change' }],
        recycleDate: [
          { validator: validateRecycleDate, trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    isView() {
      return this.$route.query.mode === 'view'
    }
  },
  created() {
    this.initForm()
  },
  methods: {
    async initForm() {
      const id = this.$route.query.id
      if (id) {
        await this.loadFileInfo(id)
      } else {
        this.resetForm()
        this.addRecord()
      }
    },
    async loadFileInfo(id) {
      try {
        const res = await getFileById(id)
        const data = res.data
        if (data) {
          // 确保records数组存在
          data.records = data.records || []
          // 格式化日期
          data.records = data.records.map(record => ({
            ...record,
            issueDate: record.issueDate ? this.formatDate(record.issueDate) : null,
            recycleDate: record.recycleDate ? this.formatDate(record.recycleDate) : null
          }))
          this.formData = data
        } else {
          this.$message.warning('未找到文件信息')
          this.resetForm()
          this.addRecord()
        }
      } catch (error) {
        console.error('获取文件信息失败:', error)
        this.$message.error('获取文件信息失败')
        this.resetForm()
        this.addRecord()
      }
    },
    resetForm() {
      this.formData = {
        id: null,
        fileCategory: '',
        pageNumber: 1,
        fileNumber: '',
        fileName: '',
        records: []
      }
    },
    addRecord() {
      this.formData.records.push({
        version: '',
        issueDate: null,
        productionCopies: 0,
        productionSignature: '',
        qualityCopies: 0,
        qualitySignature: '',
        engineeringCopies: 0,
        engineeringSignature: '',
        materialControlCopies: 0,
        materialControlSignature: '',
        researchCopies: 0,
        researchSignature: '',
        businessCopies: 0,
        businessSignature: '',
        photoelectricCopies: 0,
        photoelectricSignature: '',
        recycleDate: null,
        recycler: ''
      })
    },
    removeRecord(index) {
      this.formData.records.splice(index, 1)
    },
    async handleSave() {
      this.saving = true
      try {
        await this.$refs.form.validate()
        await saveFile(this.formData)
        this.$message.success('保存成功')
        this.goToList()
      } catch (error) {
        if (error === false) {
          this.$message.warning('请完善必填信息')
        } else {
          console.error('保存失败:', error)
          this.$message.error('保存失败')
        }
      } finally {
        this.saving = false
      }
    },
    handleAdd() {
      this.resetForm()
      this.addRecord()
      this.$message.success('已重置表单，请填写新文件信息')
    },
    goToList() {
      this.$router.push('/main/biao/ffhuishousList')
    },
    goBack() {
      this.$router.push('/main/renshi/zhaoping/zhaopingxiudin')
    },
    recyclePickerOptions(issueDate) {
      return {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }],
        disabledDate(time) {
          return time.getTime() > Date.now() || (issueDate && time.getTime() < new Date(issueDate).getTime());
        }
      };
    },
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
  </script>
  
<style lang="scss" scoped>
.form-container {
  padding: 20px;
  background-color: antiquewhite;
  min-height: calc(100vh - 40px);
}

.header {
  text-align: left;
  position: relative;
  margin-bottom: 20px;
  width: 1200px;
  margin: 0 auto;
}

.back-btn {
  transform: translateY(-50%);
}

h1 {
  text-align: center;
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.main-form {
  max-width: 1200px;
  margin: 0 auto;
}

.form-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.record-count {
  font-size: 13px;
  color: #909399;
}

.header-operations {
  display: flex;
  gap: 8px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.record-table {
    width: 100%;
    margin-bottom: 20px;
  }
  
.table-form-item {
  margin-bottom: 0;
}

.department-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}

.copies-input {
  min-width: 80px;
}

.signature-input {
  width: calc(100% - 0px);
}

.recycle-cell {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.footer {
  text-align: center;
}

.form-info {
  margin: 20px 0;
  color: #606266;
  font-size: 14px;
}

.button-group {
  margin-top: 20px;
}

.button-group .el-button {
  min-width: 100px;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-form-item__error) {
  position: absolute;
  top: 100%;
  left: 0;
  padding-top: 2px;
}

:deep(.el-input-number.is-controls-right .el-input__inner) {
  padding-left: 5px;
  padding-right: 25px;
} 
::v-deep .el-form-item {
  .el-form-item__content {
    margin-left: 0px !important;
  }
  }
  </style>